import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as authApi from '@/api/modules/auth'
import type { User, LoginRequest, RegisterRequest } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const user = ref<User | null>(null)
  const loading = ref(false)
  const avatarVersion = ref(Date.now()) // 头像版本号，用于强制刷新缓存

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.userType === 'ADMIN')
  const isVip = computed(() => user.value?.userType === 'VIP' || user.value?.userType === 'ADMIN')
  const canCreateTeam = computed(() => user.value?.userType === 'VIP' || user.value?.userType === 'ADMIN')

  // 登录
  const login = async (loginData: LoginRequest) => {
    loading.value = true
    try {
      const response = await authApi.login(loginData)
      const { token: newToken, user: userData } = response.data

      // 先保存token，再保存用户信息
      token.value = newToken
      localStorage.setItem('token', newToken)
      user.value = userData

      // 调试：打印用户信息到控制台
      console.log('=== 登录成功，用户信息 ===')
      console.log('完整用户对象:', userData)
      console.log('用户ID:', userData.id)
      console.log('用户名:', userData.username)
      console.log('角色字段 (role):', userData.role)
      console.log('用户类型字段 (userType):', userData.userType)
      console.log('权限字段 (permissions):', userData.permissions)
      console.log('所有字段:', Object.keys(userData))
      console.log('========================')

      ElMessage.success('登录成功')
      return true
    } catch (error: any) {
      console.error('登录失败:', error)

      // 不在这里显示错误信息，让调用方处理
      // 这样可以更好地处理不同类型的错误
      throw error
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerData: RegisterRequest) => {
    loading.value = true
    try {
      await authApi.register(registerData)
      ElMessage.success('注册成功，请登录')
      return true
    } catch (error: any) {
      console.error('注册失败:', error)

      // 不在这里显示错误信息，让调用方处理
      // 这样可以更好地处理不同类型的错误
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    if (!token.value) return

    try {
      const response = await authApi.getCurrentUser()
      user.value = response.data

      // 调试：打印用户信息到控制台
      console.log('=== 获取用户信息成功 ===')
      console.log('完整用户对象:', response.data)
      console.log('用户ID:', response.data.id)
      console.log('用户名:', response.data.username)
      console.log('角色字段 (role):', response.data.role)
      console.log('用户类型字段 (userType):', response.data.userType)
      console.log('权限字段 (permissions):', response.data.permissions)
      console.log('所有字段:', Object.keys(response.data))
      console.log('========================')

      // 自动登录成功时，设置在线状态
      try {
        const sessionId = "auto_session_" + Date.now() + "_" + response.data.id
        const clientInfo = {
          loginType: "AUTO_LOGIN",
          loginTime: new Date().toISOString()
        }

        // 调用后端设置在线状态的API
        await authApi.setUserOnline(response.data.id, sessionId, clientInfo)
        console.log('✅ 自动登录在线状态设置成功')
      } catch (onlineError) {
        console.error('❌ 自动登录在线状态设置失败:', onlineError)
        // 在线状态设置失败不影响登录流程
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除token
      logout()
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      user.value = null
      localStorage.removeItem('token')

      // 只有当前不在登录页时才跳转
      if (!window.location.pathname.includes('/auth/login')) {
        window.location.href = '/auth/login'
      }
    }
  }

  // 初始化 - 如果有token，获取用户信息
  const init = async () => {
    if (token.value && !user.value) {
      await getCurrentUser()
    }
  }

  return {
    // 状态
    token,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    isVip,
    canCreateTeam,
    
    // 方法
    login,
    register,
    getCurrentUser,
    logout,
    init,

    // 头像相关
    updateAvatarVersion: () => {
      avatarVersion.value = Date.now()
    },
    avatarVersion: computed(() => avatarVersion.value)
  }
})
